package com.ohuang.test_compose.page

import android.view.ViewTreeObserver
import android.view.WindowInsets
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.unit.dp
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

@Composable
fun KeyboardOverlapsContent() {

    Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
        val imeState=rememberImeState()
        val scrollState=rememberScrollState()

        LaunchedEffect(key1 = imeState.value ){
            if (imeState.value){
                scrollState.animateScrollTo(scrollState.maxValue)
            }
        }
        Column(modifier = Modifier.verticalScroll(scrollState)) {
            var text by remember { mutableStateOf("") }
            Box(modifier = Modifier
                .fillMaxWidth()
                .height(500.dp)
                .background(Color.Green))
            Text(text = "输入框：")
            TextField(value = text, onValueChange = { text = it })
            Text(text = "输入框2：")
            TextField(value = text, onValueChange = { text = it })
            Button(onClick = { }) {
                Text(text = "确定")
            }
        }
    }


}


@Composable
fun rememberImeState(): State<Boolean> {
    val imeState = remember {
        mutableStateOf(false)
    }
    val view = LocalView.current
    DisposableEffect(key1 = view) {
        val listener = ViewTreeObserver.OnGlobalLayoutListener {
            val isKeyboardOpen =
                ViewCompat.getRootWindowInsets(view)?.isVisible(WindowInsetsCompat.Type.ime())
                    ?: true
            imeState.value = isKeyboardOpen
        }
        view.viewTreeObserver.addOnGlobalLayoutListener(listener)
        onDispose {
            view.viewTreeObserver.removeOnGlobalLayoutListener(listener)
        }
    }
    return imeState
}
